<template>
  <!-- 横向滚动容器 -->
  <div class="chart-scroll-container">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script>
// 导入 ECharts
import * as echarts from "echarts";

export default {
  name: "LineChart",
  props: {
    // 图表数据，格式: [{time: '时间', value: 数值}, ...] 或直接传入数值数组
    chartData: {
      type: Array,
      default: () => [],
      required: false,
    },
    // 图表标题
    title: {
      type: String,
      default: "",
    },
    // 数据单位
    unit: {
      type: String,
      default: "单位: 人",
    },
    // 图表高度
    height: {
      type: Number,
      default: 200,
    },
    // 初始显示的数据比例
    initialVisiblePercent: {
      type: Number,
      default: 50,
    },
    // 图表线条颜色
    lineColor: {
      type: String,
      default: "#155bd4",
    },
    // 图表区域填充渐变色
    areaGradient: {
      type: Array,
      default: () => [
        { offset: 0, color: "rgba(21, 91, 212, 0.3)" },
        { offset: 1, color: "rgba(21, 91, 212, 0.1)" },
      ],
    },
    // 是否显示最大值标记
    showMaxMark: {
      type: Boolean,
      default: true,
    },
    // 容器样式控制
    position: {
      type: String,
      default: "relative",
      validator: (value) => ["relative", "absolute", "fixed"].includes(value),
    },
    left: {
      type: String,
      default: "0%",
    },
    right: {
      type: String,
      default: "0%",
    },
    top: {
      type: String,
      default: "0%",
    },
    bottom: {
      type: String,
      default: "0%",
    },
    // 图表位置控制
    gridLeft: {
      type: String,
      default: "3%",
    },
    gridRight: {
      type: String,
      default: "4%",
    },
    gridTop: {
      type: String,
      default: "10%",
    },
    gridBottom: {
      type: String,
      default: "15%",
    },
  },
  data() {
    return {
      chart: null,
      resizeTimer: null,
    };
  },
  computed: {
    // 容器样式
    // containerStyle() {
    //   return {
    //     height: `${this.height}px`,
    //     position: this.position,
    //     left: this.left,
    //     right: this.right,
    //     top: this.top,
    //     bottom: this.bottom
    //   };
    // }
  },
  mounted() {
    // 等待DOM渲染完成后初始化图表
    this.$nextTick(() => {
      this.initChart();
      // 监听窗口大小变化
      window.addEventListener("resize", this.handleResize);
    });
  },
  beforeDestroy() {
    // 清理资源
    window.removeEventListener("resize", this.handleResize);
    if (this.resizeTimer) {
      clearTimeout(this.resizeTimer);
    }
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    // 初始化图表
    initChart() {
      const chartDom = this.$refs.chartRef;
      if (!chartDom) return;

      this.chart = echarts.init(chartDom);

      // 准备数据
      let xAxisData = [];
      let seriesData = [];

      // 如果有传入数据，则使用传入的数据
      if (this.chartData && this.chartData.length > 0) {
        if (
          typeof this.chartData[0] === "object" &&
          this.chartData[0].hasOwnProperty("time")
        ) {
          // 处理对象数组格式: [{time: '时间', value: 数值}, ...]
          xAxisData = this.chartData.map((item) => item.time);
          seriesData = this.chartData.map((item) => item.value);
        } else {
          // 处理简单数值数组，生成默认时间标签
          seriesData = this.chartData;
          for (let i = 0; i < seriesData.length; i++) {
            xAxisData.push(`${i}:00`);
          }
        }
      } else {
        // 如果没有传入数据，生成默认的24小时数据
        for (let i = 0; i < 24; i++) {
          xAxisData.push(`${i}:00`);
          // 生成随机数据，保持波动趋势
          let baseValue = 150;
          if (i >= 2 && i <= 6) baseValue = 100; // 凌晨低值
          if (i >= 8 && i <= 10) baseValue = 200; // 上午高峰
          if (i >= 18 && i <= 22) baseValue = 180; // 晚上高峰
          seriesData.push(baseValue + Math.floor(Math.random() * 50) - 25);
        }
      }

      const option = {
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            return params[0].name + "<br/>在线人数: " + params[0].value + "人";
          },
        },
        // 启用 dataZoom 组件实现滚动
        dataZoom: [
          {
            type: "slider",
            show: true,
            xAxisIndex: [0],
            height: 20,
            bottom: 5,
            start: 0,
            end: 50, // 初始显示50%的数据
            zoomLock: false,
            handleIcon:
              "M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z",
            handleSize: "80%",
            handleStyle: {
              color: "#fff",
              shadowBlur: 3,
              shadowColor: "rgba(0, 0, 0, 0.6)",
              shadowOffsetX: 2,
              shadowOffsetY: 2,
            },
          },
        ],
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%", // 增加底部空间给滚动条
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: "#dcdfe6",
            },
          },
          axisLabel: {
            color: "#606266",
          },
        },
        yAxis: {
          type: "value",
          name: "单位: 人",
          min: 0,
          max: 250,
          axisLine: {
            lineStyle: {
              color: "#dcdfe6",
            },
          },
          axisLabel: {
            color: "#606266",
          },
          splitLine: {
            lineStyle: {
              color: "#f0f2f5",
            },
          },
        },
        series: [
          {
            name: "在线人数",
            type: "line",
            smooth: true,
            symbolSize: 8,
            data: seriesData,
            lineStyle: {
              color: "#155bd4",
              width: 3,
            },
            itemStyle: {
              color: "#155bd4",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(21, 91, 212, 0.3)",
                },
                {
                  offset: 1,
                  color: "rgba(21, 91, 212, 0.1)",
                },
              ]),
            },
            markPoint: {
              data: [
                {
                  type: "max",
                  name: "最大值",
                },
              ],
              itemStyle: {
                color: "#155bd4",
              },
              label: {
                formatter: function (params) {
                  return `${params.name}\n在线人数: ${params.value}`;
                },
              },
            },
          },
        ],
      };

      this.chart.setOption(option);
    },

    // 处理窗口大小变化
    handleResize() {
      // 使用防抖避免频繁重绘
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer);
      }
      this.resizeTimer = setTimeout(() => {
        if (this.chart) {
          this.chart.resize();
        }
      }, 100);
    },
  },
};
</script>

<style scoped>
/* .line-chart-container {
  width: 100%;
  height: 100%;
  position: relative;
} */

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.chart-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.chart-unit {
  font-size: 12px;
  color: #606266;
}

.chart-container {
  width: 100%;
  height: 200px;
  /* // 为了能滚动，设置一个较大的最小宽度 */
  min-width: 575px;
}
/* // 添加横向滚动容器样式 */
.chart-scroll-container {
  overflow-x: auto;
  overflow-y: hidden;
  /* // 隐藏滚动条但保持功能（可选） */
  &::-webkit-scrollbar {
    height: 6px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #555;
  }
}
.chart-card.trend-chard {
  margin-left: 10px;
  width: 100%;
}
</style>
